<!--  -->
<template>
  <div>
    <div>
      <!-- {{ params }}      {{ props.dialogVisible }} -->
      <slot :params="params" :searchSubmit="searchSubmit" :TypeList="TypeList" :StateList="StateList" name="search">
      </slot>
    </div>
    <div>
      <slot :deleteAllHandle="deleteAllHandle" name="buttons"></slot>
    </div>
    <div>
      <el-table v-loading="loading" @selection-change="handleSelectionChange" :data="datas.list" style="width: 100%">
        <el-table-column v-if="props.isSelection" type="selection" width="40" />
        <el-table-column class="table-column" v-for="column in props.columns" :prop="column.prop" :label="column.label"
          v-bind="column.attrs">

          <!-- 插槽 自定义字段 -->
          <template v-if="column.slot" #default="scope">
            <slot :name="column.prop" :deleteHandle="deleteHandle" :scope="scope"></slot>
          </template>
          <!-- 时间格式化 -->
          <template v-if="column.timeFormat" #default="scope">
            {{ formatTime(scope.row[column.prop], column.timeFormat) }}
          </template>

          <template v-if="column.state" #default="scope">
             <el-switch v-model="scope.row.state" :active-value="1" :inactive-value="0"  />
          </template>

          <!-- 单张图片 -->
          <template v-if="column.image" #default="scope">
            <el-image style="width: auto; height:40px" :src="imgBaseUrl + scope.row[column.prop]" :zoom-rate="1.2"
              :max-scale="7" :min-scale="0.2" preview-teleported
              :preview-src-list="[imgBaseUrl + scope.row[column.prop]]" :initial-index="4" fit="cover" />
          </template>
          <!-- 多张图片 -->
          <template v-if="column.images" #default="scope">
            <el-image v-for="item in scope.row[column.prop]" style="width: auto; height:40px;margin-left:10px;"
              :src="imgBaseUrl + item.url" :zoom-rate="1.2" :max-scale="7" :min-scale="0.2" preview-teleported
              :preview-src-list="scope.row[column.prop].map((item: any) => imgBaseUrl + item.url)" :initial-index="4"
              fit="cover" />
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-pagination v-if="props.pageConfig.isShow" @size-change="handleSizeChange" @current-change="handleCurrentChange"
      class="page" v-model:current-page="params.page" v-model:page-size="params.psize"
      :page-sizes="props.pageConfig.pageSizes" background layout="total, sizes, prev, pager, next, jumper"
      :total="datas.total" />
  </div>
</template>

<script lang='ts' setup>
const imgBaseUrl = ref(import.meta.env.VITE_IMG_URL);
import { reactive, ref, onMounted, defineEmits, defineExpose } from 'vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import { watch } from 'vue';
import moment from 'moment';

const formatTime = (val: string, format: string) => {
  return moment(val).format(format);
}

type ColumnType = {
  prop: string,
  label: string,
  slot?: boolean,
  attrs?: any,
  image?: boolean,
  images?: boolean
  timeFormat?: string | undefined,
  state?: boolean,
}
type PageConfig = {
  psize?: number,
  isShow?: boolean,
  pageSizes?: number[],
}
export type TableType = {
  columns: Array<ColumnType>,
  loadData: Function,
  delete?: Function,
  type?: Function,
  state?: Function,
  deleteAll?: Function,
  pageConfig?: PageConfig,
  searhParams?: any,
  isSelection?: boolean,
  dialogVisible?: any
}

const loading = ref(false);
//接收传过来的列
const props = withDefaults(defineProps<TableType>(), {
  columns: () => [],
  loadData: () => () => { },
  delete: () => () => { },
  type: () => () => { },
  state: () => () => { },
  deleteAll: () => () => { },
  pageConfig: () => ({
    psize: 15,
    isShow: true,    //是否显示分页
    pageSizes: [15, 30, 50, 100, 300]
  }),
  searhParams: () => ({}),
  isSelection: true,   //是否显示多选框
  dialogVisible: false
})
console.log("322323", props);
watch(() => props.dialogVisible, (newValue, oldValue) => {
  console.log('person的job变化了', newValue, oldValue)
  params.page = 1;
  getData()
}, { deep: true })

//

if (props.pageConfig.psize == undefined) {
  props.pageConfig.psize = 15;
}
if (props.pageConfig.isShow == undefined) {
  props.pageConfig.isShow = true;
}
if (props.pageConfig.pageSizes == undefined) {
  props.pageConfig.pageSizes = [15, 30, 50, 100, 300];
}
console.log(props.pageConfig);

// const isSelection=ref(true)


const params = reactive<any>({
  page: 1,
  psize: props.pageConfig.psize

})

interface List$1Type {
  id: number
  title: string
  picture: string
  edituser: string
  state: number
  type: number
  hits: number
  typename: string
  content: null
  addtime: string
}

interface Result$0Type {
  "total": number
  list: Array<List$1Type>
}


const datas: Result$0Type = reactive({
  total: 0,
  list: []
})
//搜索
const searchSubmit = () => {
  params.page = 1;
  getData();
}

//获取数据
const getData = async () => {
  loading.value = true;
  let _params = { ...props.searhParams, ...params };
  const res: any = await props.loadData(_params);
  console.log("9999", _params);

  console.log("9999", res);
  if (res.errCode === 10000) {
    datas.list = res.data.list;
    datas.total = res.data.counts;


    stateList.value = datas.list.map(item => item.state)
    console.log(stateList.value);

  }
  console.log(res.data.list);
  loading.value = false;
}
//单个删除
const deleteHandle = async (id: number) => {
  const confirm = await ElMessageBox.confirm('是否要删除该条记录?').catch(() => { })
  if (!confirm) return;
  const res: any = await props.delete(id).catch(() => { });
  if (res.errCode === 10000) {
    ElMessage.success("删除成功");
    getData();
  }
}
const emit = defineEmits(["multipleSelection"])
//多选
const multipleSelection = ref<any[]>([])
const handleSelectionChange = (val: any[]) => {
  multipleSelection.value = val
  emit("multipleSelection", val);
}
//批量删除
const deleteAllHandle = async () => {
  if (!multipleSelection.value.length) {
    ElMessage.error('请选择要删除的记录');
    return;
  }
  const confirm = await ElMessageBox.confirm('是否要删除选中的记录?').catch(() => { })
  if (!confirm) return;
  let ids = multipleSelection.value.map(item => item.id);
  const res: any = await props.deleteAll(ids).catch(() => { });
  if (res.errCode === 10000) {
    ElMessage.success("删除成功");
    getData();
  }
}
//分页事件
const handleSizeChange = (val: number) => {
  params.psize = val;
  getData();
}
const handleCurrentChange = (val: number) => {
  params.page = val;
  getData();
}
//类型
const TypeList: any = ref([])
const getRepairsTypeList = async () => {
  const res = await props.type();
  console.log(456789, res.data?.list);
  TypeList.value = res.data?.list
}
//状态
const StateList: any = ref([])
const getRepairStateList = async () => {
  const res = await props.state();
  console.log("111", res.data?.list);
  StateList.value = res.data?.list
}

let stateList: any = ref([])


onMounted(() => {
  getData();
  if (props.type) getRepairsTypeList()
  if (props.state) getRepairStateList()
})
//导出数据或方法供父组件调用ref
defineExpose({ getData, params, TypeList, StateList, datas });
</script>
<style scoped>
.page {
  margin: 30px 0px;
  display: flex;
  justify-content: center;
}

.el-table__cell {
  color: rgba(0, 0, 0, 0.88);
  font-weight: 600;
  font-size: 13px;
}
</style>